package com.demo.servlet.demo1215;

import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/demo1215/ajax02.do")
public class Ajax02Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String school = request.getParameter("school");
        String param1 = request.getParameter("param1");
        String param2 = request.getParameter("param2");
        response.getWriter().write("响应成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String school = request.getParameter("school");
        String param1 = request.getParameter("param1");
        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().write("你好");
        List<Student> students = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            students.add(new Student(i, "学生" + i, i + 18, "实验小学"));
        }
        Gson gson = new Gson();
        //List 对象转换成 JSON 字符串
        String studentsStr = gson.toJson(students);
        response.getWriter().write(studentsStr);
    }
}
